package com.xiaoxin.yixinai.companyinfo;

import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.xiaoxin.yixinai._frame.base.BaseController;
import com.xiaoxin.yixinai._frame.base.ModuleCode;
import com.xiaoxin.yixinai._frame.base.PageSupport;
import com.xiaoxin.yixinai._frame.utils.StringUtils;
import com.xiaoxin.yixinai.companyversion.CompanyVersionService;
import com.xiaoxin.yixinai.dict.DictService;
import com.xiaoxin.yixinai.userinfo.UserInfo;
import com.xiaoxin.yixinai.userinfo.UserInfoService;

@Controller
@RequestMapping("/company")
public class CompanyInfoController extends BaseController {
	
	@Resource
	private CompanyInfoService companyInfoService;

	@Resource
	private UserInfoService userInfoService;
	
	@Resource
	protected DictService dictService;
	
	@Resource
	private CompanyVersionService companyVersionService;
	
	
	/**
	 * 查询代理商的公司
	 * @param agentId 代理商
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/list4agentId", method = RequestMethod.POST)
	public Object findByAgentId(Integer agentId) {
		if (agentId == null) {
			return ERROR("empty");
		} else {
			List<CompanyInfo> companyList = companyInfoService.findByAgentsIdOrderByCompanyId(agentId);
			return SUCCESS(companyList);
		}
	}
	
	
	/**
	 * 系统工程师查询公司列表
	 * @param keyword
	 * @param model
	 * @param pagesupport
	 * @return
	 */
	@PreAuthorize("hasAuthority('company')")
	@ModuleCode(pValue="operations", value="company")
	@RequestMapping(value = "/systemlist",method = RequestMethod.GET)
	public Object systemlist(@RequestParam(defaultValue="0")Integer keywordType
			, @RequestParam(defaultValue="") String keyword, ModelMap model, PageSupport pagesupport) {
		
		Sort sort = new Sort(Direction.DESC, "companyId");
		Page<CompanyInfo> page = companyInfoService.findByKeyword(keywordType, keyword.trim(), pagesupport.getPage(sort));
		/* 查询登录名  */
		List<CompanyInfo> list = page.getContent();
		if (list != null && list.size() > 0) {
			Set<Integer> companyIds = list.stream().map(c -> c.getCompanyId()).collect(Collectors.toSet());
			List<UserInfo> userList = userInfoService.findManagerByCompanyIdIn(companyIds);
			// 有些公司的管理员被删除了以后，这个方法下面的部分就要出错了，页面就会显示500。至少不让页面显示500吧，所以这里判断一下。
			if (userList != null && !userList.isEmpty()) {
				Map<Integer, UserInfo> userInfoMap = userList.stream().collect(Collectors.toMap(UserInfo::getCompanyId, Function.identity()));
				for (CompanyInfo c : list) {
					UserInfo userInfo = userInfoMap.get(c.getCompanyId());
					if (userInfo != null) {
						c.setManageUserId(userInfo.getUserId());
						c.setUserName(userInfo.getUserName());
						c.setLoginName(userInfo.getLoginName());
					}
				}
			}
		}
		
		Map<String, String> dict = dictService.findMapByInfoType("theWordsType");
		/* 通过公司id集合查询通道数 */
		Map<String,Integer> channelNumMap = new HashMap<String,Integer>();
		if(page.getContent() != null && page.getContent().size() > 0) {
			Set<Integer> companyIds = page.getContent().stream().map(c -> c.getCompanyId()).collect(Collectors.toSet());
			channelNumMap = companyInfoService.findChannelNumByCompanyIds(companyIds);
		}
		
		model.addAttribute("page", page);
		model.addAttribute("dict", dict);
		model.addAttribute("keyword", keyword.trim());
		model.addAttribute("keywordType", keywordType);
		model.addAttribute("channelNumMap", channelNumMap);
		
		return "/companysystem/list";
	}
	
	
	/**
	 * 重置密码跳转
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/resetPassWordJump", method = RequestMethod.GET)
	public String resetPassWordJump(ModelMap model,Integer companyId) {
		model.addAttribute("companyId", companyId);
		return "/company/restpwdjump";
	}
	
	/**
	 * 验证 公司名称是否重复
	 * @param companyId
	 * @param companyNname
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/verifyCompanyNameUnique", method = RequestMethod.POST)
	public Object verifyCompanyNameUnique(Integer companyId,@RequestParam(defaultValue="") String companyName) {
		if (StringUtils.isEmpty(companyName)) {
			return ERROR("empty");
		} else {
			CompanyInfo companyInfo = companyInfoService.verifyCompanyNameUnique(companyId, companyName.trim());
			if(null == companyInfo) {
				return SUCCESS();
			}else {
				return ERROR("repeat");
			}
		}
	}
	
	/**
	 * 卡券管理-发放-查询发放对象
	 * @param companyName
	 * @param provinceCode
	 * @param cityCode
	 * @param pagesupport
	 * @param model
	 * @return
	 * @throws ParseException
	 */
	@ResponseBody
	@RequestMapping(value = "/grantCardCompany", method = RequestMethod.POST)
	public Object grantCardCompany(@RequestParam(defaultValue="") String companyName, String provinceCode, String cityCode, Integer industryId
			, PageSupport pagesupport) {
		
		// 查询列表数据
		Page<CompanyInfo> page = companyInfoService.find4GrantCardCompany(companyName.trim(), provinceCode, cityCode, industryId, pagesupport.getPage());
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("content", page.getContent());
		map.put("pageNum", page.getNumber());
		map.put("pageSize", page.getSize());
		map.put("totalElements", page.getTotalElements());
		map.put("totalPages", page.getTotalPages());
		return SUCCESS(map);
	}
	
	
}
